using System.Net;
using System.Text;
using Jurassic.Library;
using Kiwi.Node.Modules.Builtin;

namespace Kiwi.Node.Modules.Http
{
    public class HttpResponse: EventEmitter
    {
        public StringBuilder Buffer { get; private set; }
        public HttpListenerResponse Response { get; set; }

        public HttpResponse(IApplication application, HttpListenerResponse response)
            : base(application)
        {
            Response = response;
            Buffer = new StringBuilder();

            Response.ContentType = "text/html";
            Response.ContentEncoding = Encoding.UTF8;
        }

        [JSFunction(Name = "write")]
        public void Write(string text)
        {
            Buffer.Append(text);
        }
        public void Close()
        {
            var output = Response.OutputStream;

            byte[] buffer = Encoding.UTF8.GetBytes(Buffer.ToString());
            Response.ContentLength64 = buffer.Length;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
            Response.Close();
            Response.Abort();
            InternalEmit("close");
        }
    }
}